<script type="text/javascript">
    var $oss_url_path = "<?php echo $this->oss_url_path; ?>";
    var $allowed_image_type = "<?php echo implode($this->allowed_image_type,','); ?>";
    var $allowed_image_size = "<?php echo $this->allowed_image_size;?>";
</script>

<header class="demo-header">
    <div class="title3Left flt text-center header-small">
        <a href="javascript:history.back(-1);" class="whiteC">
            <img src="/img/back.png" class="backimg">返回
        </a>
    </div>
    <div class="title3Middle flt text-center">添加产品</div>
    <div class="title3Right flt text-center header-small" id="bianji">保存</div>
</header>
<div class="whitebg">
    <input type="radio" name="myradio" value="random_name" checked hidden/> <!--随机生成文件名称，支持多次重复上传-->
    <form id="productData" onsubmit="return false">
        <input type="hidden" name="id">
       <div class="message-detail paddingnot">
            <p>
                商品名称<span class="product">(必填)</span>
                <input class="input" id="cnee" name="name" value="<?php echo isset($this->info->name) ? $this->info->name : '' ?>" type="text" placeholder="请输入商品名称" maxlength="30" required>
            </p>
            <p class="border1">
                商品单价<span class="product">(必填)</span>
                <input class="input" id="cnee-tel"name="unit_price" value="<?php echo (isset($this->info->unit_price) && (int)$this->info->unit_price !=0) ? $this->info->unit_price : '' ?>"  type="number" placeholder="￥0.00" maxlength="30" required>
            </p>
            <p class="border1">
                <span hidden id="img_id_area">
                    <?php if(isset($this->info->image_list)):?>
                        <?php foreach ($this->info->image_list as $image): ?>
                            <input type="hidden" name="image_id_list[]" value="<?php echo  $image->id ?>">
                        <?php endforeach;?>
                    <?php endif;?>
               </span>
                商品图片<span class="Cgray header-small">(最多上传5张)</span>
            </p>
            <div class="return-order-img" style="padding-left: 65px;">
                <div class="uploadImg filecommen" >
                    <span id="img_area">
                        <?php if(isset($this->info->image_list)):?>
                            <?php foreach ($this->info->image_list as $image): ?>
                                <input type="hidden" name="image_id_list[]" value="<?php echo  $image->id ?>">
                                <label class="result">
                                    <img class="img_val img-width" src="<?php echo  $image->url ?>"/><img src="/img/close_icon.png" product_id="<?php echo  $image->id ?>" class="del" title="\u5220\u9664"/>
                                </label>
                            <?php endforeach;?>
                        <?php endif;?>
                    </span>
                    <label id="add_img">+</label>
                    <a id="add_img_action" hidden></a>
                </div>
            </div>
            <div class="graybg data-padding"></div>
            <p>
                商品描述
                <textarea class="beizhu-area" name="describe" id="cnee-tel" type="text" placeholder="请输入商品描述" ><?php echo isset($this->info->describe) ? $this->info->describe : '' ?></textarea>
            </p>
        </div>
    </form>
</div>
<script type="text/javascript" src="/js/plupload.full.min.js"></script>
<!--<script type="text/javascript" src="/js/oss-web-upload.js"></script>-->
<script type="text/javascript">
    // 素材上传 ios 特殊处理
    var u = navigator.userAgent;
    var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    if (isiOS) {
        iosInit();
    }

    function iosInit() {
        $('#add_img').live('click',function () {
            var file_ele = $('#img_area').find('input[type="file"]');
//            file_ele.attr('accept','audio/*'); // 加入之后选择文件的框弹出较慢
            file_ele.click();
        });
    }

    $('#bianji').click(function () {
        var id = "<?php echo $this->info->id ?>";
        var name = $('input[name="name"]').val();
        var unit_price = $('input[name="unit_price"]').val();
        var describe = $('input[name="describe"]').val();

        if (id == false ) {alert('id 不能为空')}
        if (name == false ) {alert('对不起，商品名称不能为空')}
        if (unit_price == false ) {alert('对不起，商品单价不能为空')}

        $('input[name="id"]').val(id);
        var url = '/product/update';
        $.post(url,$('#productData').serializeArray(),function (res) {
            if (res.code != 200) {
            } else {
                window.location.href ='/article/edit?id=<?php echo isset($this->info->article_id) ? $this->info->article_id : '' ?>';
            }
        },'json');
    });

    $(".uploadImg .del").live('click',function() {
        $(this).parent().remove();
        var product_id = $(this).attr('product_id');
        $('input[value="'+product_id+'"]').remove();

    });

        // 阿里云oss web 直传，优点 web 断 object 直接上传到 阿里云oss ，不经过闪广服务器端，节省流量，还可保证上传速度。
    // 详细文档地址 服务端签名直传并设置上传回调 https://help.aliyun.com/document_detail/31927.html?spm=5176.doc31926.6.630.aVSm0V
    accessid = ''
    accesskey = ''
    host = ''
    policyBase64 = ''
    signature = ''
    callbackbody = ''
    filename = ''
    key = ''
    expire = 0
    g_object_name = ''
    g_object_name_type = ''
    now = timestamp = Date.parse(new Date()) / 1000;

    function send_request()
    {
        var xmlhttp = null;
        if (window.XMLHttpRequest)
        {
            xmlhttp=new XMLHttpRequest();
        }
        else if (window.ActiveXObject)
        {
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }

        if (xmlhttp!=null)
        {
            serverUrl = '/article/ossini'
            xmlhttp.open( "GET", serverUrl, false );
            xmlhttp.send( null );
            return xmlhttp.responseText
        }
        else
        {
            alert("Your browser does not support XMLHTTP.");
        }
    };

    function check_object_radio() {
        var tt = document.getElementsByName('myradio');
        for (var i = 0; i < tt.length ; i++ )
        {
            if(tt[i].checked)
            {
                g_object_name_type = tt[i].value;
                break;
            }
        }
    }

    function get_signature()
    {
        //可以判断当前expire是否超过了当前时间,如果超过了当前时间,就重新取一下.3s 做为缓冲
        now = timestamp = Date.parse(new Date()) / 1000;
        if (expire < now + 3)
        {
            body = send_request()
            var obj = eval ("(" + body + ")");
            host = obj['host']
            policyBase64 = obj['policy']
            accessid = obj['accessid']
            signature = obj['signature']
            expire = parseInt(obj['expire'])
            callbackbody = obj['callback']
            key = obj['dir']
            return true;
        }
        return false;
    };

    function random_string(len) {
        len = len || 32;
        var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
        var maxPos = chars.length;
        var pwd = '';
        for (i = 0; i < len; i++) {
            pwd += chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
    }

    function get_suffix(filename) {
        pos = filename.lastIndexOf('.')
        suffix = ''
        if (pos != -1) {
            suffix = filename.substring(pos)
        }
        return suffix;
    }

    function calculate_object_name(filename)
    {
        if (g_object_name_type == 'local_name')
        {
            g_object_name += "${filename}"
        }
        else if (g_object_name_type == 'random_name')
        {
            suffix = get_suffix(filename)
            g_object_name = key + random_string(10) + suffix
        }
        return ''
    }

    function get_uploaded_object_name(filename)
    {
        if (g_object_name_type == 'local_name')
        {
            tmp_name = g_object_name
            tmp_name = tmp_name.replace("${filename}", filename);
            return tmp_name
        }
        else if(g_object_name_type == 'random_name')
        {
            return g_object_name
        }
    }

    function set_upload_param(up, filename, ret,content_type)
    {
        if (ret == false)
        {
            ret = get_signature()
        }
        g_object_name = key;
        if (filename != '') {
            suffix = get_suffix(filename)
            calculate_object_name(filename)
        }

        new_multipart_params = {
            'key' : g_object_name,
            'policy': policyBase64,
            'OSSAccessKeyId': accessid,
            'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
            'callback' : callbackbody,
            'signature': signature,
            "x:type":content_type, // 自定义参数区分内容类型  desc :https://helpcdn.aliyun.com/document_detail/31989.html
            "x:product_id":<?php echo $this->info->id; ?>, // 自定义参数区分内容类型  desc :https://helpcdn.aliyun.com/document_detail/31989.html
        };

        up.setOption({
            'url': host,
            'multipart_params': new_multipart_params
        });
        up.start();
    }

    /**
     * 添加商品页面上传图片
     * @type {Uploader}
     */
    var uploaderProductImg = new plupload.Uploader({
        runtimes : 'html5,flash,silverlight,html4',
        browse_button : 'add_img',
        multi_selection: true,
        container: document.getElementById('img_area'),
        flash_swf_url : 'lib/plupload-2.1.2/js/Moxie.swf',
        silverlight_xap_url : 'lib/plupload-2.1.2/js/Moxie.xap',
        url : 'http://oss.aliyuncs.com',
        filters: {
            mime_types : [
//                { title : "Image files", extensions : $allowed_image_type }, //加了之后手机上（照片）无法上传
            ],
            max_file_size : $allowed_image_size, //最大只能上传10mb的文件
            prevent_duplicates : false //允许选取重复文件
        },

        init: {
            PostInit: function() {
                document.getElementById('add_img_action').onclick = function() {
                    set_upload_param(uploaderProductImg, '', false, 'product');
                    return false;
                };
            },

            FilesAdded: function(up, files) {
                plupload.each(files, function(file) {
                    $('#add_img_action').click();// 发送oss请求
                });
            },

            BeforeUpload: function(up, file) {
                check_object_radio();
                set_upload_param(up, file.name, true, 'product');
            },

            UploadProgress: function(up, file) {

            },
            FileUploaded: function(up, file, info) {

                if (info.status == 200)
                {
                    var res_data = $.parseJSON(info.response);
                    if (res_data) {
                        var img_id = res_data.CallInfo.id;
                        $('#img_id_area').append('<input type="hidden" name="image_id_list[]" value="'+img_id+'"/>');
                    }
                    var delsrc='/img/close_icon.png';
                    var html = '<label class="result" style="border:none">'+
                                    '<img class="img_val img-width" src="'+$oss_url_path+'/'+get_uploaded_object_name(file.name)+'"/><img src="'+delsrc+'" product_id="'+img_id+'" class="del" title="\u5220\u9664"/>'+
                                '</label>';

                    $('#img_area').append(html);
                }
                else
                {
                    alert('上传文件出错：'+info.response);
                }
            },

            Error: function(up, err) {
                if (err.code == -600) {
                    alert("对不起，选择的文件太大了");
                }
                else if (err.code == -601) {
                    alert("对不起，暂不支持此种类型文件上传");
                }
                else if (err.code == -602) {
                    alert("\n对不起，这个文件已经上传过一遍了");
                }
                else
                {
                    alert("\nError xml:" + err.response);
                }
            }
        }
    });
    uploaderProductImg.init();
</script>

